package com.example.demo.controller;

import com.example.demo.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class LoginController {
    private final UserService userService;

    public LoginController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/login")
    public String loginPage() {
        return "login";
    }

    @PostMapping("/doLogin")
    public String doLogin(
            @RequestParam String username,
            @RequestParam String password,
            Model model
    ) {
        if (userService.login(username, password)) {
            model.addAttribute("username", username);
            return "index";
        } else {
            model.addAttribute("error", "用户名或密码错误");
            return "login";
        }
    }
}